package com.scuec.groupfive.controller;

import com.scuec.groupfive.entity.MockExam;
import com.scuec.groupfive.service.MockExamRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/mock-exams")
@CrossOrigin
public class MockExamRecordController {

    @Autowired
    private MockExamRecordService mockExamRecordService;

    @GetMapping("/user/{userId}")
    public List<MockExam> getByUserId(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        return mockExamRecordService.getMockExamRecordsByUserId(userId, page, size);
    }

    @GetMapping("/search")
    public List<MockExam> search(
            @RequestParam Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        return mockExamRecordService.searchMockExamRecords(
                userId, startDate, endDate, keyword, page, size
        );
    }

    @GetMapping("/detail/{examId}")
    public Map<String, Object> getMockExamRecordDetail(@PathVariable Long examId) {
        return mockExamRecordService.getMockExamRecordDetail(examId);
    }
    // MockExamRecordController.java

    // 在原有内容基础上新增：
    @PostMapping("/favorite")
    public ResponseEntity<?> toggleFavorite(
            @RequestBody Map<String, Object> requestBody) { // 使用@RequestBody接收JSON

        Long questionId = Long.valueOf(requestBody.get("questionId").toString());
        Boolean isFavorite = Boolean.valueOf(requestBody.get("isFavorite").toString());
        Long userId = Long.valueOf(requestBody.get("userId").toString());

        mockExamRecordService.toggleFavorite(userId, questionId, isFavorite);
        return ResponseEntity.ok().build();
    }
}